<script setup lang="ts">
import { computed, ref, watch } from 'vue';

import { message } from 'ant-design-vue';

// 接口定义
interface BillItem {
  id: string;
  name: string;
  specification: string;
  unit: string;
  quantity: number;
  unitPrice: number;
  discountedPrice: number;
  total: number;
  salesPerson: string;
  servicePerson: string;
  category: string;
  date: string;
  serviceTimes: number; // 改为必需属性
}

interface Bill {
  id: string;
  petName: string;
  petId: string;
  ownerName: string;
  ownerPhone: string;
  createTime: string;
  status: 'onAccount' | 'refund' | 'settled' | 'unsettled';
  totalAmount: number;
  items: BillItem[];
}

interface ServiceCard {
  id: string;
  name: string;
  totalTimes: number;
  remainingTimes: number;
  validUntil: string;
}

interface Props {
  visible: boolean;
  bill: Bill | null;
}

interface Emits {
  (e: 'update:visible',value: boolean): void;
  (e: 'success'): void;
}

const props = defineProps<Props>();
const emit = defineEmits<Emits>();

// 响应式数据
const selectedCard = ref<string>('');
const selectedRowKeys = ref<string[]>([]);
const autoPrint = ref(false);
const isInitialized = ref(false); // 添加初始化标志
const isMaximized = ref(false); // 添加最大化状态

// 服务人员选项
const servicePersonOptions = [
  { label: '张美容师', value: '张美容师' },
  { label: '李美容师', value: '李美容师' },
  { label: '王美容师', value: '王美容师' },
  { label: '赵美容师', value: '赵美容师' },
  { label: '陈美容师', value: '陈美容师' },
  { label: '刘美容师', value: '刘美容师' },
];

// 模拟次卡数据
const availableCards = ref<ServiceCard[]>([
  {
    id: '1',
    name: '美容次卡A',
    totalTimes: 10,
    remainingTimes: 5,
    validUntil: '2024-12-31',
  },
  {
    id: '2',
    name: '美容次卡B',
    totalTimes: 20,
    remainingTimes: 8,
    validUntil: '2024-12-31',
  },
  {
    id: '3',
    name: '洗澡次卡C',
    totalTimes: 15,
    remainingTimes: 12,
    validUntil: '2024-12-31',
  },
  {
    id: '4',
    name: '护理次卡D',
    totalTimes: 8,
    remainingTimes: 3,
    validUntil: '2024-12-31',
  },
  {
    id: '5',
    name: '美容套餐卡E',
    totalTimes: 30,
    remainingTimes: 18,
    validUntil: '2024-12-31',
  },
]);

// 计算属性
const visible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value),
});

const selectedCardInfo = computed(() => {
  return availableCards.value.find((card) => card.id === selectedCard.value);
});

// 将billItems改为ref，避免频繁重新计算
const billItems = ref<BillItem[]>([]);

// 初始化billItems的函数
const initializeBillItems = () => {
  if (!props.bill) {
    billItems.value = [];
    isInitialized.value = false;
    return;
  }

  // 如果已经初始化过且数据存在，不重复初始化
  if (isInitialized.value && billItems.value.length > 0) {
    return;
  }

  // 获取账单中的美容服务项目
  const groomingItems = props.bill.items
    .filter((item) => item.category === 'grooming')
    .map((item) => ({
      ...item,
      serviceTimes: 1,
      servicePerson: '',
    }));

  // 如果没有美容服务项目，添加一些模拟数据
  billItems.value =
    groomingItems.length === 0
      ? [
          {
            id: 'grooming-1',
            name: '长毛犬美容',
            specification: '8-12kg',
            unit: '次',
            quantity: 1,
            unitPrice: 200,
            discountedPrice: 200,
            total: 200,
            salesPerson: '李美容师',
            servicePerson: '',
            category: 'grooming',
            date: props.bill.createTime.split(' ')[0],
            serviceTimes: 1,
          },
          {
            id: 'grooming-2',
            name: '短毛犬美容',
            specification: '5-8kg',
            unit: '次',
            quantity: 1,
            unitPrice: 150,
            discountedPrice: 150,
            total: 150,
            salesPerson: '李美容师',
            servicePerson: '',
            category: 'grooming',
            date: props.bill.createTime.split(' ')[0],
            serviceTimes: 1,
          },
          {
            id: 'grooming-3',
            name: '宠物洗澡',
            specification: '标准洗护',
            unit: '次',
            quantity: 1,
            unitPrice: 80,
            discountedPrice: 80,
            total: 80,
            salesPerson: '张美容师',
            servicePerson: '',
            category: 'grooming',
            date: props.bill.createTime.split(' ')[0],
            serviceTimes: 1,
          },
          {
            id: 'grooming-4',
            name: '宠物造型',
            specification: '精修造型',
            unit: '次',
            quantity: 1,
            unitPrice: 120,
            discountedPrice: 120,
            total: 120,
            salesPerson: '王美容师',
            servicePerson: '',
            category: 'grooming',
            date: props.bill.createTime.split(' ')[0],
            serviceTimes: 1,
          },
          {
            id: 'grooming-5',
            name: '宠物护理',
            specification: '深度护理',
            unit: '次',
            quantity: 1,
            unitPrice: 100,
            discountedPrice: 100,
            total: 100,
            salesPerson: '赵美容师',
            servicePerson: '',
            category: 'grooming',
            date: props.bill.createTime.split(' ')[0],
            serviceTimes: 1,
          }
        ]
      : groomingItems

  // 标记为已初始化
  isInitialized.value = true
};

const itemColumns = [
  {
    title: '项目名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '数量',
    dataIndex: 'quantity',
    key: 'quantity',
  },
  {
    title: '服务次数',
    dataIndex: 'serviceTimes',
    key: 'serviceTimes',
  },
  {
    title: '服务人员',
    dataIndex: 'servicePerson',
    key: 'servicePerson',
  },
];

// 移除不需要的表格列定义
// const itemColumns = [...];

// 移除不需要的rowSelection
// const rowSelection = computed(() => ({...}));

const totalTimes = computed(() => {
  return billItems.value
    .filter((item) => selectedRowKeys.value.includes(item.id))
    .reduce((sum, item) => sum + (item.serviceTimes || 1), 0);
});

const remainingTimes = computed(() => {
  if (!selectedCardInfo.value) return 0;
  return selectedCardInfo.value.remainingTimes - totalTimes.value;
});

// 方法
const handleCardChange = (cardId: string) => {
  selectedCard.value = cardId;
  // 只重置选择状态，不重置用户输入的数据
  selectedRowKeys.value = [];
  // 不重置 serviceTimes 和 servicePerson，保持用户输入
};

const handleCardClick = (event: MouseEvent) => {
  // 检查点击的目标元素
  const target = event.target as HTMLElement;

  // 如果点击的是输入框、选择框、复选框等交互元素，不触发卡片选择
  if (
    target.closest('.ant-input-number') ||
    target.closest('.ant-select') ||
    target.closest('.ant-checkbox') ||
    target.closest('input') ||
    target.closest('select')
  ) {
    return;
  }

  // 获取当前卡片的itemId
  const cardElement = target.closest('.item-card') as HTMLElement;
  if (cardElement) {
    const itemId = cardElement.dataset.itemId;
    if (itemId) {
      toggleItemSelection(itemId);
    }
  }
};

const toggleItemSelection = (itemId: string) => {
  const index = selectedRowKeys.value.indexOf(itemId);
  if (index === -1) {
    selectedRowKeys.value.push(itemId);
  } else {
    selectedRowKeys.value.splice(index, 1);
  }
};

const handleItemCheckboxChange = (itemId: string, checked: boolean) => {
  if (checked) {
    if (!selectedRowKeys.value.includes(itemId)) {
      selectedRowKeys.value.push(itemId);
    }
  } else {
    const index = selectedRowKeys.value.indexOf(itemId);
    if (index !== -1) {
      selectedRowKeys.value.splice(index, 1);
    }
  }
};

const handleServicePersonChange = () => {
  // 服务人员变化时的处理，可以在这里添加额外的逻辑
  // 目前不需要特殊处理，因为v-model已经自动更新了数据
};

const handleServiceTimesChange = (value: number) => {
  // 服务次数变化时的处理
  // 确保值在有效范围内
  if (value < 1) {
    value = 1;
  }
  if (selectedCardInfo.value && value > selectedCardInfo.value.remainingTimes) {
    value = selectedCardInfo.value.remainingTimes;
  }
  // 由于使用了v-model，这里不需要手动更新，但可以添加验证逻辑
};

const updateTotalTimes = () => {
  // 更新总次数计算 - 由于使用了计算属性，这里不需要额外处理
  // totalTimes 计算属性会自动响应 serviceTimes 的变化
};

const showRechargeModal = () => {
  message.info('充值功能开发中...');
};

const toggleMaximize = () => {
  isMaximized.value = !isMaximized.value;
};

const handleOk = () => {
  if (!selectedCard.value) {
    message.warning('请选择次卡');
    return;
  }

  if (selectedRowKeys.value.length === 0) {
    message.warning('请选择要结算的项目');
    return;
  }

  if (totalTimes.value > (selectedCardInfo.value?.remainingTimes || 0)) {
    message.warning('服务次数超过剩余次数');
    return;
  }

  // 检查服务人员是否已选择
  const unassignedItems = billItems.value.filter(
    (item) => selectedRowKeys.value.includes(item.id) && !item.servicePerson,
  );

  if (unassignedItems.length > 0) {
    message.warning('请为所有选中项目选择服务人员');
    return;
  }

  message.success('次卡结算成功');
  emit('success');
  emit('update:visible', false);
  resetForm();
};

const handleCancel = () => {
  emit('update:visible', false);
  resetForm();
};

const resetForm = () => {
  selectedCard.value = '';
  selectedRowKeys.value = [];
  autoPrint.value = false;
  // 不重置 billItems，避免用户输入的数据丢失
};

// 监听模态框打开，只在首次打开时初始化数据
watch(
  () => props.visible,
  (newVisible, oldVisible) => {
    if (newVisible && !oldVisible) {
      // 只在模态框首次打开时初始化
      resetForm();
      initializeBillItems();
    }
  },
);

// 监听账单变化，只在账单真正改变时重新初始化数据
watch(
  () => props.bill?.id,
  (newBillId, oldBillId) => {
    if (props.visible && newBillId !== oldBillId) {
      // 只在账单ID真正改变时重新初始化
      initializeBillItems();
    }
  },
);
</script>

<template>
  <a-modal
    v-model:open="visible"
    title="次卡结算"
    :width="isMaximized ? '90vw' : '700px'"
    :style="{ top: isMaximized ? '5vh' : '100px' }"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <template #title>
      <div
        style="
          display: flex;
          align-items: center;
          justify-content: space-between;
          width: 100%;
        "
      >
        <span>次卡结算</span>
        <a-button
          type="text"
          size="small"
          @click="toggleMaximize"
          style="margin-left: 8px"
        >
          <template #icon>
            <span v-if="isMaximized">⛶</span>
            <span v-else>⛶</span>
          </template>
        </a-button>
      </div>
    </template>
    <div class="service-card-modal" :class="{ maximized: isMaximized }">
      <!-- 次卡选择 -->
      <div class="card-selection">
        <h4>选择次卡</h4>
        <div class="selection-row">
          <a-select
            v-model:value="selectedCard"
            placeholder="选择次卡"
            style="width: 300px"
            @change="handleCardChange"
          >
            <a-select-option
              v-for="card in availableCards"
              :key="card.id"
              :value="card.id"
            >
              {{ card.name }} (剩余{{ card.remainingTimes }}次)
            </a-select-option>
          </a-select>
          <a-button type="link" @click="showRechargeModal"> 充值 </a-button>
        </div>
      </div>

      <!-- 项目选择 -->
      <div class="item-selection">
        <h4>选择项目 (*仅结算已勾选的项目)</h4>
        <div class="items-grid">
          <div
            v-for="item in billItems"
            :key="item.id"
            class="item-card"
            :class="{ selected: selectedRowKeys.includes(item.id) }"
            :data-item-id="item.id"
            @click="handleCardClick"
          >
            <div class="item-header">
              <a-checkbox
                :checked="selectedRowKeys.includes(item.id)"
                @change="
                  (e) => handleItemCheckboxChange(item.id, e.target.checked)
                "
                @click.stop
              />
              <div class="item-info">
                <div class="item-name">{{ item.name }}</div>
                <div class="item-spec">{{ item.specification }}</div>
              </div>
              <div class="item-price">¥{{ item.unitPrice }}</div>
            </div>

            <div class="item-details">
              <div class="detail-row">
                <span class="label">服务次数:</span>
                <a-input-number
                  v-model:value="item.serviceTimes"
                  :min="1"
                  :max="selectedCardInfo?.remainingTimes || 1"
                  size="small"
                  style="width: 80px"
                  :precision="0"
                  :controls="true"
                  :disabled="false"
                  @change="handleServiceTimesChange"
                  @click.stop
                  @mousedown.stop
                  @mouseup.stop
                  @focus.stop
                  @blur.stop
                />
              </div>
              <div class="detail-row">
                <span class="label">服务人员:</span>
                <a-select
                  v-model:value="item.servicePerson"
                  size="small"
                  style="width: 120px"
                  placeholder="选择人员"
                  :options="servicePersonOptions"
                  @click.stop
                  @change="handleServicePersonChange"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 结算信息 -->
      <div class="settlement-info">
        <div class="info-row">
          <span class="label">支付次数:</span>
          <span class="value">{{ totalTimes }}次</span>
        </div>
        <div class="info-row">
          <span class="label">剩余次数:</span>
          <span class="value">{{ remainingTimes }}次</span>
        </div>
      </div>

      <!-- 底部选项 -->
      <div class="bottom-options">
        <a-checkbox v-model:checked="autoPrint">
          结算完成后自动打印
        </a-checkbox>
      </div>
    </div>
  </a-modal>
</template>

<style scoped>
.service-card-modal {
  padding: 16px 0;
}

.card-selection,
.item-selection,
.settlement-info {
  margin-bottom: 24px;
}

.card-selection h4,
.item-selection h4 {
  margin: 0 0 16px;
  font-size: 16px;
  color: #333;
}

.selection-row {
  display: flex;
  gap: 12px;
  align-items: center;
}

.settlement-info {
  padding: 16px;
  background: #f8f9fa;
  border-radius: 6px;
}

.info-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 8px;
}

.info-row:last-child {
  margin-bottom: 0;
}

.info-row .label {
  font-size: 14px;
  color: #666;
}

.info-row .value {
  font-weight: 500;
  color: #333;
}

.bottom-options {
  padding-top: 16px;
  margin-top: 16px;
  border-top: 1px solid #e8e8e8;
}

/* 项目卡片网格布局 */
.items-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  max-height: 400px;
  padding: 8px 0;
  overflow-y: auto;
}

/* 最大化时的网格布局 */
.service-card-modal.maximized .items-grid {
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  max-height: 60vh;
}

.item-card {
  padding: 16px;
  cursor: pointer;
  background: white;
  border: 2px solid #e8e8e8;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.item-card:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgb(24 144 255 / 10%);
}

.item-card.selected {
  background: #f0f8ff;
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgb(24 144 255 / 20%);
}

.item-header {
  display: flex;
  gap: 12px;
  align-items: flex-start;
  margin-bottom: 12px;
}

.item-info {
  flex: 1;
}

.item-name {
  margin-bottom: 4px;
  font-weight: 500;
  color: #333;
}

.item-spec {
  font-size: 12px;
  color: #666;
}

.item-price {
  font-size: 16px;
  font-weight: 600;
  color: #1890ff;
}

.item-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-row {
  display: flex;
  gap: 8px;
  align-items: center;
  justify-content: space-between;
}

.detail-row .label {
  min-width: 60px;
  font-size: 12px;
  color: #666;
}
</style>
